/*
 * 文件简单通信协议：
 *  1）4 字节的文件名字节数（int）
 *  2）文件名（UTF-8 编码）
 *  3）8 字节的文件字节数（long）
 *  4）文件内容
 */

package addition.file;

import addition.utils.FileUtils;
import lombok.NonNull;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class FileClient {

    public static void sendFile(@NonNull File file, @NonNull OutputStream os) throws IOException {
        // File info
        String filename = file.getName();  // File name
        long fileLength = file.length();  // File length

        // Wrap OutputStream to DataOutputStream
        DataOutputStream dos = new DataOutputStream(os);

        // Write file info
        dos.writeInt(filename.length());  // filename length
        dos.write(filename.getBytes(StandardCharsets.UTF_8));  // filename body
        dos.writeLong(fileLength);  // file length

        System.out.println("> FILENAME: " + filename);
        System.out.println("> FILE_LENGTH: " + fileLength);
        System.out.println("> FILENAME_LENGTH: " + filename.length());

        // Write file body
        int len;
        byte[] buffer = new byte[1024 * 4];
        try (FileInputStream fis = new FileInputStream(file)) {
            while ((len = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, len);
            }
        }

        dos.close();
        System.out.println("> SEND OK");
    }

    public static void main(String[] args) {
        String path = FileUtils.getRootFilePath("wallhaven-z85gyw.jpg");
        System.out.println("> PATH: " + path);
        try (Socket socket = new Socket("127.0.0.1", 8080)) {
            // Send File to Server
            sendFile(new File(path), socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
